package com.leoman.creator.controller;

import com.leoman.city.entity.City;
import com.leoman.city.service.CityService;
import com.leoman.common.controller.common.GenericEntityController;
import com.leoman.common.factory.DataTableFactory;
import com.leoman.creator.entity.Creator;
import com.leoman.creator.entity.CreatorImage;
import com.leoman.creator.service.CreatorImageService;
import com.leoman.creator.service.CreatorService;
import com.leoman.creator.service.impl.CreatorServiceImpl;
import com.leoman.creatordynamic.entity.Dynamic;
import com.leoman.dynamic.service.DynamicService;
import com.leoman.entity.Configue;
import com.leoman.entity.Constant;
import com.leoman.entity.FileBo;
import com.leoman.exception.GeneralExceptionHandler;
import com.leoman.province.entity.Province;
import com.leoman.province.service.ProvinceService;
import com.leoman.sensitivewords.service.SensitiveWordsService;
import com.leoman.user.entity.UserInfo;
import com.leoman.user.entity.UserLogin;
import com.leoman.user.service.UserLoginService;
import com.leoman.user.service.UserService;
import com.leoman.utils.*;
import com.leoman.vcode.VcodeService;
import com.leoman.work.entity.WorkCreator;
import com.leoman.work.service.WorkCreatorService;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 蔡琦 on 2016/6/15 0015.
 */
@Controller
@RequestMapping(value = "admin/creator")
public class CreatorController extends GenericEntityController<Creator, Creator, CreatorServiceImpl> {

    @Autowired
    private CreatorService creatorService;

    @Autowired
    private CreatorImageService creatorImageService;

    @Autowired
    private WorkCreatorService workCreatorService;

    @Autowired
    private UserService userService;

    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private ProvinceService provinceService;

    @Autowired
    private CityService cityService;

    @Autowired
    private VcodeService vcodeService;

    @Autowired
    private UserLoginService userLoginService;

    @Autowired
    private SensitiveWordsService sensitiveWordsService;

    /**
     * 列表页面
     *
     * @return path
     */
    @RequestMapping(value = "/index")
    public String index() {
        return "creator/list";
    }

    /**
     * 查询列表
     */
    @RequestMapping(value = "/list")
    public void list(HttpServletResponse response,
                     String mobile,
                     String nickname,
                     Integer gender,
                     Integer status,
                     String startDate,
                     String endDate,
                     Integer draw,
                     Integer start,
                     Integer length) {
        try {
            int pageNum = getPageNum(start, length);

            Page<UserInfo> page = userService.page(mobile, nickname, gender, status, null, startDate, endDate, Constant.IF_CREATOR_YES, null, pageNum, length);
            List<UserInfo> list = page.getContent();
            List<WorkCreator> workCreatorList;
            for (UserInfo userInfo : list) {
                // 查询主创的作品数
                workCreatorList = workCreatorService.findByUserId(userInfo.getId());
                if (workCreatorList == null) {
                    userInfo.setNum(0);
                }
                userInfo.setNum(workCreatorList != null ? workCreatorList.size() : 0);
            }
            Map<String, Object> result = DataTableFactory.fitting(draw, page);
            WebUtil.print(response, result);
        } catch (Exception e) {
            GeneralExceptionHandler.log(e);
            WebUtil.print(response, emptyData);
        }
    }

    /**
     * 封禁
     */
    @RequestMapping(value = "/banned")
    @ResponseBody
    public Integer banned(Long userId, Integer status) {

        UserInfo userInfo = userService.queryByPK(userId);
        userInfo.setStatus(status);
        userService.update(userInfo);

        return 1;
    }

    /**
     * 推荐到艺人区
     */
    @RequestMapping(value = "/setCreator")
    @ResponseBody
    public Integer setCreator(Long userId, Integer status) {

        UserInfo userInfo = userService.queryByPK(userId);
        Creator creator = userInfo.getCreator();
        creator.setStatus(status);

        creatorService.update(creator);

        return 1;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail")
    public String detail(Long userId, Model model) {

        creatorService.detail(userId, model);

        return "creator/detail";
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    public String add(Model model) {
        model.addAttribute("creatorImageList", JSONArray.fromObject(new ArrayList<Map<String, Object>>()));
        return "creator/add";
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/edit")
    public String edit(Long userId, Model model) {
        try {
            Map<String, Object> map = new HashMap<>();
            List<Map<String, Object>> list = new ArrayList<>();

            UserInfo userInfo = userService.queryByPK(userId);
            if (StringUtils.isNotEmpty(userInfo.getAvater())) {
                userInfo.setAvater(ImageUtil.clearUploadUrl(userInfo.getAvater()));
            }
            if (StringUtils.isNotEmpty(userInfo.getCreator().getCoverUrl())) {
                userInfo.getCreator().setCoverUrl(ImageUtil.clearUploadUrl(userInfo.getCreator().getCoverUrl()));
            }

            // 主创图片
            List<CreatorImage> creatorImageList = creatorImageService.findByCreatorId(userInfo.getCreator().getId());
            for (CreatorImage creatorImage : creatorImageList) {
                if (StringUtils.isNotEmpty(creatorImage.getImage())) {
                    map = new HashMap<>();
                    map.put("id", creatorImage.getId());
                    map.put("type", creatorImage.getType());
                    map.put("path", ImageUtil.clearUploadUrl(creatorImage.getImage()));
                }

                list.add(map);
            }

            // 主创动态
            List<Dynamic> dynamicList = dynamicService.findByCreatorId(userInfo.getCreator().getId());

            model.addAttribute("userInfo", userInfo);
            model.addAttribute("dynamicList", dynamicList);
            model.addAttribute("creatorImageList", JSONArray.fromObject(list));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "creator/add";
    }

    /**
     * 查询省份列表
     */
    @RequestMapping(value = "/provinceList")
    @ResponseBody
    public List<Province> provinceList() {

        return provinceService.iFindList();
    }

    /**
     * 查询城市列表
     */
    @RequestMapping(value = "/cityList")
    @ResponseBody
    public List<City> cityList(Long provinceId) {

        return cityService.findById(provinceId);
    }

    /**
     * 上传缓存图片
     */
    @RequestMapping("/addTempImage")
    @ResponseBody
    public CreatorImage addTempImage(MultipartRequest multipartRequest, Integer type) {
        CreatorImage image = new CreatorImage();

        try {
            MultipartFile multipartFile = multipartRequest.getFile("tempImage");

            // 验证图片格式
            String originalFileName = multipartFile.getOriginalFilename().toLowerCase();
            String fileType = originalFileName.substring(originalFileName.indexOf("."));

            List<String> list = new ArrayList<>();
            list.add(".jpg");
            list.add(".gif");
            list.add(".jpeg");
            list.add(".png");
            list.add(".bmp");

            if (!list.contains(fileType)) {
                return image;
            }

            FileBo fileBo = FileUtil.save(multipartFile, true);
            image.setImage(fileBo.getPath());
            image.setSuolue(fileBo.getSuoluePath());
            image.setType(type);

            creatorImageService.save(image);
            image.setImage(ImageUtil.clearUploadUrl(fileBo.getPath()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return image;
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Integer save(Long id,
                        String nickname,
                        String password,
                        Integer gender,
                        Integer isCreator,
                        Long provinceId,
                        Long cityId,
                        String description,
                        String weibo,
                        String experience,
                        String[] time,
                        String[] thing,
                        String tempAddImageIds1,
                        String tempAddImageIds2,
                        String tempDelImageIds,
                        String[] times,
                        String[] things,
                        MultipartRequest multipartRequest) {

        try {

            // 过滤敏感字符
            nickname = sensitiveWordsService.replaceWord(nickname);
            description = sensitiveWordsService.replaceWord(description);
            weibo = sensitiveWordsService.replaceWord(weibo);
            experience = sensitiveWordsService.replaceWord(experience);
            for (int i = 0; i < thing.length; i++) {
                thing[i] = sensitiveWordsService.replaceWord(thing[i]);
            }
            if (things != null) {
                for (int i = 0; i < things.length; i++) {
                    things[i] = sensitiveWordsService.replaceWord(things[i]);
                }
            }

            // 保存主创
            return creatorService.saveAll(id, nickname, password, gender, isCreator, provinceId, cityId, description, weibo, experience, time, thing,
                    tempAddImageIds1, tempAddImageIds2, tempDelImageIds, times, things, multipartRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 批量禁用
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    @ResponseBody
    public Integer deleteBatch(String ids) {
        Long[] arrayId = JsonUtil.json2Obj(ids, Long[].class);
        for (Long id : arrayId) {
            UserInfo userInfo = userService.queryByPK(id);
            userInfo.setStatus(Constant.USER_STATUS_FREEZE);
            userService.save(userInfo);
        }
        return 1;
    }

    /**
     * 删除动态
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Integer delete(Long id) {

        Dynamic dynamic = dynamicService.queryByPK(id);
        dynamicService.delete(dynamic);

        return 1;
    }

    private static Map<String, String> codeMap = new HashMap<>();

    static {
        if (codeMap == null || codeMap.isEmpty()) {
            codeMap = new HashMap<>();
        }
    }

    /**
     * 发送验证码
     */
    @RequestMapping(value = "/sendCode")
    @ResponseBody
    public Integer sendCode(String num) {
        if (!StringUtils.isNotEmpty(num)) {
            return 0;
        }
        String code = RandomUtil.getCode(6);
        if (vcodeService.sendKX(code, num)) {
            codeMap.put(num, code);
            return 1;
        } else {
            return 2;
        }
    }

    /**
     * 绑定手机
     */
    @RequestMapping(value = "/mobile")
    @ResponseBody
    public Integer mobile(Long userId, String num, String code) {

        String requestCode = codeMap.get(num);
        if (StringUtils.isBlank(code)) {
            // 验证码为空
            return 2;
        }

        if (!requestCode.equals(code)) {
            // 验证码错误
            return 3;
        }

        UserLogin userLogin1 = userLoginService.findByMobile(num);
        if (userLogin1 != null) {
            // 账号已存在
            return 4;
        }

        UserInfo userInfo = userService.queryByPK(userId);
        userInfo.setMobile(num);

        userService.update(userInfo);

        if (StringUtils.isNotEmpty(userInfo.getPassword())) {
            UserLogin userLogin = new UserLogin();
            userLogin.setUsername(userInfo.getMobile());
            userLogin.setPassword(userInfo.getPassword());
            userLoginService.save(userLogin);

            userInfo.setUserLogin(userLogin);
            userService.update(userInfo);
        }
        return 1;
    }
}
